package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    @Override
    public Result queryById(Long id) {
        Blog blog = getById(id);

        if(blog == null){
            return Result.fail("笔记不存在");
        }

        queryBlogUser(blog);
        isBlogLiked(blog);
        return Result.ok(blog);
    }


    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result likeBlog(Long id) {
        // redis的sortedset中,文章的id作为key,用户id作为数据来记录谁点过赞

        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        Long userId = user.getId();
        // 从redis的点赞列表中查询,看看是否用户已经对文章点赞过
        String key = BLOG_LIKED_KEY+id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());

        if(score == null){
            // 如果没点赞过,那么点击就是点赞,数据库点赞数加1
            // 将用户添加到redis中
            boolean success = update().setSql("liked = liked + 1 ").eq("id", id).update();
            if(success){
                stringRedisTemplate.opsForZSet().add(key, userId.toString(),System.currentTimeMillis());
            }
        }else{
            // 如果已经点赞过了,那么再点击就是取消点赞,数据库点赞数减1
            // 把用户从redis的set中移除
            boolean success = update().setSql("liked = liked - 1 ").eq("id", id).update();
            if(success) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return Result.ok();
    }


    @Override
    public Result queryBlogLikes(Long id) {
        // 在redis中根据博客的id找到记录,查询点赞的前五名用户的id
        String key = BLOG_LIKED_KEY+id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(top5 == null || top5.isEmpty()){
            return Result.ok(Collections.emptyList());
        }

        // 然后根据id从数据库中查出用户数据并封装到userDto类中
        List<Long> userIds = top5.stream().map(Long::valueOf).collect(Collectors.toList());

        String ids = StrUtil.join(",",userIds);
        List<UserDTO> collect = userService.query().in("id",userIds).last("ORDER BY FIELD(id,"+ids+")").list()
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());

        // 将5名用户封装到list中返回给前端
        return Result.ok(collect);

    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean success = save(blog);
        if(!success){
            return Result.fail("新增笔记失败");
        }
        // 查询作者的粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        // 向每个粉丝推送
        for(Follow follow : follows){
            Long userId = follow.getUserId();
            // 每个粉丝的推件箱,key就是每个推件箱的key
            String key = FEED_KEY+userId;
            // 推送箱子记录博客的id,还有推送博客的时间戳
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }

        // 返回id
        return Result.ok(blog.getId());
    }

    // 查询用户关注的用户新发的笔记
    // max是上次查询的笔记的时间戳,用来实现滚动分页的,如果是第一次查询,那么时间戳是当前时间
    // offset是偏移量,也是用来实现滚动查询功能的
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 获取当前用户
        Long userid = UserHolder.getUser().getId();
        // 查询当前用户的收件箱
        String key = FEED_KEY+userid;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);

        if(typedTuples == null || typedTuples.isEmpty()){
            return Result.ok();
        }

        List<Long> ids = new ArrayList<>(typedTuples.size());
        long mintime = 0;
        int cnt=1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            ids.add(Long.valueOf(typedTuple.getValue()));
            long score = typedTuple.getScore().longValue();
            if(mintime == score){
                cnt++;
            }
            else{
                cnt = 1;
            }
            mintime = score;
        }


        // 按顺序取出笔记
        String idStr = StrUtil.join(",",ids);
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();

        // 设置笔记的相关信息
        for (Blog blog : blogs) {
            queryBlogUser(blog);
            isBlogLiked(blog);
        }

        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setOffset(cnt);
        scrollResult.setMinTime(mintime);
        scrollResult.setList(blogs);

        return Result.ok(scrollResult);
    }


    // 查询出该笔记的发布者的头像和昵称
    public void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());
    }

    // 查询出当前登录用户是否对此笔记点赞过
    public void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if(user== null){
            // 如果当前用户还未登录,那么不需要判断是否点过赞
            return;
        }
        Long userId=user.getId();
        String key = "blog:liked:"+userId;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score!=null);
    }
}
